package leetcode

import (
	"ecode/structures"
)

// ListNode define
// type ListNode struct {
//	 Val  int
//	 Next *ListNode
// }
type ListNode = structures.ListNode

func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
	head := &ListNode{}

	if l1 == nil || l2 == nil {
		return nil
	}

	a1 := l1.Val
	a2 := l2.Val
	h := 0
	p := head

	for {
		sum := a1 + a2 + h
		h, p.Val = sum/10, sum%10

		if l1.Next == nil && l2.Next == nil && h == 0 {
			break
		}

		if l1.Next == nil {
			a1 = 0
		} else {
			l1 = l1.Next
			a1 = l1.Val
		}

		if l2.Next == nil {
			a2 = 0
		} else {
			l2 = l2.Next
			a2 = l2.Val
		}

		p.Next = &ListNode{}
		p = p.Next
	}

	return head
}
